package com.huike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.dto.ContractDto;
import com.huike.entity.Activity;
import com.huike.entity.Contract;
import com.huike.entity.Course;
import com.huike.entity.SysDictData;
import com.huike.mapper.ActivityMapper;
import com.huike.mapper.ContractMapper;
import com.huike.mapper.CourseMapper;
import com.huike.mapper.SysDictDataMapper;
import com.huike.result.PageResult;
import com.huike.result.Result;
import com.huike.service.ContractService;
import com.huike.utils.AliOssUtil;
import com.huike.vo.ContractVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Override
    public Result<PageResult> queryPage(ContractDto contractDto) {

        if (contractDto.getPage() == null || contractDto.getPageSize() == null) {
            contractDto.setPage(1);
            contractDto.setPageSize(10);
        }
        IPage<Contract> iPage = new Page<>(contractDto.getPage(), contractDto.getPageSize());

        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();

        if (contractDto.getContractId() != null) {
            queryWrapper.lambda().like(Contract::getContractNo, contractDto.getContractId());
        }
        if (contractDto.getCustomerName() != null) {
            queryWrapper.lambda().like(Contract::getName, contractDto.getCustomerName());
        }
        if (contractDto.getPhone() != null) {
            queryWrapper.lambda().like(Contract::getPhone, contractDto.getPhone());
        }

        if (contractDto.getBeginTime() != null && contractDto.getEndTime() != null) {

            LocalDateTime localDateTime = contractDto.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();

            LocalDateTime startTime = LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MAX);

            queryWrapper.lambda().between(Contract::getCreateTime, startTime,endTime);


            queryWrapper.lambda().between(Contract::getCreateTime, contractDto.getBeginTime(), contractDto.getEndTime());
        }

        if (contractDto.getPurchaseCourse() != null) {
            queryWrapper.lambda().eq(Contract::getCourseName, contractDto.getPurchaseCourse());
            // subject,字典
        }
        if (contractDto.getPurchaseSubject() != null) {
            queryWrapper.lambda().eq(Contract::getSubject, contractDto.getPurchaseSubject());
            // subject,字典
        }

        IPage<Contract> page = contractMapper.selectPage(iPage, queryWrapper);

        PageResult<Contract> pageResult = new PageResult<>(page.getTotal(), page.getRecords());

        return Result.success(pageResult);


    }

    @Override
    public Result purchaseCourseList(String subject) {


        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.lambda().eq(Course::getSubject,subject);
        List<Course> courses = courseMapper.selectList(courseQueryWrapper);
        return Result.success(courses);
    }

    @Override
    public Result purchaseSubjectList() {

        QueryWrapper<SysDictData> dictDataQueryWrapper = new QueryWrapper<>();
        dictDataQueryWrapper.lambda().eq(SysDictData::getDictType, "course_subject");
        List<SysDictData> subjectList = sysDictDataMapper.selectList(dictDataQueryWrapper);
        return Result.success(subjectList);
    }

    @Override
    public Result channelList() {
        QueryWrapper<SysDictData> dictDataQueryWrapper = new QueryWrapper<>();
        dictDataQueryWrapper.lambda().eq(SysDictData::getDictSort, "clues_item");
        List<SysDictData> subjectList = sysDictDataMapper.selectList(dictDataQueryWrapper);
        return Result.success(subjectList);
    }

    @Override
    public Result activityList(String id) {
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        activityQueryWrapper.lambda().eq(Activity::getStatus,0);
        activityQueryWrapper.lambda().eq(Activity::getDetail,id);
        List<Activity> activityList = activityMapper.selectList(activityQueryWrapper);
        return Result.success(activityList);
    }

    @Override
    public Result purchaseCourseGetList() {

        List<Course> courses = courseMapper.selectList(null);

        ArrayList<Course> subjectCourseList = courses.stream()
                .collect(Collectors
                        .collectingAndThen(Collectors
                                .toCollection(() -> new TreeSet<>(Comparator
                                        .comparing(Course::getSubject))), ArrayList::new));

        //升序
        List<Course> list = subjectCourseList.stream().sorted(Comparator.comparing(Course::getId)).collect(Collectors.toList());
        //List<Course> list = subjectCourseList.stream().sorted(Comparator.comparing(Course::getId).reversed()).collect(Collectors.toList());

        return Result.success(list);
    }

    @Override
    public Result<String> uploadPDF(MultipartFile file) {
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.pdf
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            if (!"pdf".equals(extension)){
                return Result.error("请上传pdf文件");
            }
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        }
    }

    @Override
    public Result insert(Contract contract) {

        contractMapper.insert(contract);
        return Result.success();
    }

    @Override
    public Result findById(Integer id) {

        Contract contract = contractMapper.selectById(id);

        ContractVo contractVo = new ContractVo();
        contractVo.setCustomerName(contract.getName());
        contractVo.setCourse(contractVo.getCourse());
        contractVo.setSubject(contractVo.getSubject());

        Activity activity = activityMapper.selectById(contract.getActivityId());
        Course course = courseMapper.selectById(contract.getCourseId());

        contractVo.setPayNum((int) (course.getPrice()-activity.getTicket()-activity.getDiscount()));
        if (activity.getDetail() != null){
            contractVo.setDetail(Integer.valueOf(activity.getDetail()));
            contractVo.setIsDiscount(1);
        }
        contractVo.setCreatedBeginTime(LocalDateTime.now());

        return Result.success(contractVo);
    }
}
